<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @clear="search"
      />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button
        v-permission="'park:enterprise:add_edit'"
        type="primary"
        @click="$router.push({ path: '/addEnterprise' })"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <!-- 绑定list进行渲染 -->

      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <!-- 展开行区域 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime }}——{{ rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formatInfoType(rentObj.row.status)">
                    {{ formatStatus(rentObj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="rentingOut(scope.row.id)"
                    :disabled="scope.row.status === 3"
                    v-permission="'park:rent:add_surrender'"
                    >退租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.row.id)"
                    :disabled="scope.row.status !== 3"
                    v-permission="'park:rent:remove'"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod()" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="addRent(scope.row.id)"
              v-permission="'park:rent:add_surrender'"
              >添加合同</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="$router.push(`/enterpriseDetail/${scope.row.id}`)"
              v-permission="'park:enterprise:query'"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="toEditPage(scope.row.id)"
              v-permission="'park:enterprise:add_edit'"
              >编辑</el-button
            >
            <!-- 表格的话按钮使用插槽，可以通过scope.row获取到当前行数据 -->
            <!-- 表格使用row相当于item -->
            <el-button
              size="mini"
              type="text"
              @click="deleteEnterprise(scope.row.id)"
              v-permission="'park:enterprise:remove'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleChange"
      />
    </div>
    <!-- 添加合同弹框 -->
    <!-- visible 弹框的显示与隐藏 -->
    <!-- @close 点击关闭的处理函数 -->
    <!-- close-on-click-modal 控制是否点击模态框关闭 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <!-- :limit 限制文件上传最大个数 -->
            <!-- :on-exeed设置文件上传最大个数后的回调 -->
            <!-- :on-remove="handleRemove" 文件被删除的回调-->
            <el-upload
              action="#"
              :http-request="uploadFile"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              ref="upload"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部插槽 -->
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitRent"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  reqGetRentBuildingAPI,
  reqGetEnterpriseListAPI,
  reqDelEnterpriseAPI,
  reqAddRentAPI,
  reqDelRentAPI,
  reqRentingOutAPI,
} from "@/api/enterprise";
import { reqQueryBuilding, reqUploadAPI } from "@/api/common";
// 使用vuex中的数据
import { mapState } from "vuex";
export default {
  created() {
    this.getEnterpriseList();
  },
  computed: {
    ...mapState("menu", ["permission"]),
  },
  data() {
    return {
      // 查询参数
      params: {
        name: "",
        page: 1,
        pageSize: 5,
      },
      // 接收结果
      list: [],
      total: 0,
      // 弹框显隐
      rentDialogVisible: false,
      // 租赁楼宇数据
      rentList: [],
      rentForm: {
        buildingId: null,
        startTime: "",
        endTime: "",
        contractUrl: "",
        contractId: null,
        type: 0,
        enterpriseId: null, //企业ID
        rentTime: [],
      },
      rentRules: {
        contractId: [
          { required: true, message: "请上传合同", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请输入起止日期", trigger: "blur" },
        ],
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 格式化状态码
    formatStatus(status) {
      const MAP = {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      };
      return MAP[status];
    },
    // 格式化标签
    formatInfoType(status) {
      const MAP = {
        0: "warning",
        1: "success",
        2: "info",
        3: "danger",
      };
      // return 格式化之后的中文显示
      return MAP[status];
    },
    // 获取合同列表
    async getEnterpriseList() {
      const res = await reqGetEnterpriseListAPI(this.params);
      this.list = res.data.rows.map((item) => {
        return {
          // 把数组里的每一个对象展开
          ...item,
          rentList: [], // 额外添加数组,存储租赁合同列表
        };
      });
      this.total = res.data.total;
    },
    handleChange(val) {
      this.params.page = val;
      this.getEnterpriseList();
    },
    indexMethod() {
      return (this.params.page - 1) * this.params.pageSize + 1;
    },
    search() {
      this.params.page = 1;
      this.getEnterpriseList();
    },
    // 跳转至编辑页面
    toEditPage(id) {
      this.$router.push({
        path: "/addEnterprise",
        // 携带id跳转
        query: { id },
      });
    },
    // 删除企业
    deleteEnterprise(id) {
      this.$confirm("此操作将永久删除该企业, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqDelEnterpriseAPI(id);
          console.log(res);
          // 若是演示数据则提示不允许删除且返回
          // if (res.code == 50000) {
          //   this.$message.error(res.msg);
          //   return;
          // }
          this.$notify.success("删除成功");
          // 判断当前页的数据是否是1，并且当前页码大于1，若是的话，就将页码减1
          if (this.list.length === 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.getEnterpriseList();
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    // 文件移除
    handleRemove(file) {
      console.log(file);
      this.rentForm.contractUrl = "";
      this.rentForm.contractId = "";
      // 移除后校验
      this.$refs.addForm.validateField("contractId");
    },
    // 点击关闭dialog的回调
    closeDialog() {
      this.rentDialogVisible = false;
      // 清空校验的数据
      this.$refs.addForm.resetFields();
      this.rentForm.contractUrl = "";
      this.rentForm.type = 0;
      this.rentForm.startTime = "";
      this.rentForm.endTime = "";
      this.rentForm.enterpriseId = null;
      // 清空文件列表
      this.$refs.upload.clearFiles();
    },
    async addRent(id) {
      this.rentDialogVisible = true;
      const res = await reqQueryBuilding();
      this.rentList = res.data;
      this.rentForm.enterpriseId = id;
    },
    // 租赁文件上传
    async uploadFile({ file }) {
      console.log(file);
      const formData = new FormData();
      // 追加参数
      formData.append("file", file);
      formData.append("type", 2);
      const res = await reqUploadAPI(formData);
      console.log(res);
      this.rentForm.contractUrl = res.data.url;
      this.rentForm.contractId = res.data.id;
      this.$refs.addForm.validateField("contractId");
    },
    // 上传前的校验
    beforeUpload(file) {
      // 文件类型白名单
      const imgType = [
        "application/pdf",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      ];
      // 检验上传文件类型是否属于以上类型
      const type = imgType.includes(file.type);
      // 检验大小是否超过5m
      // 文件个数1个
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (type && isLt5M) {
        return true;
      } else {
        this.$message.error("上传文件不符合要求，请重新上传！");
        return false;
      }
    },
    // 超出限制的回调
    handleExceed() {
      this.$message.warning("文件个数超出限制！");
    },
    // 提交
    submitRent() {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) {
          this.$message.error("请填写完整信息！");
          return;
        }
        // 数组解构
        const [startTime, endTime] = this.rentForm.rentTime;
        this.rentForm.startTime = startTime;
        this.rentForm.endTime = endTime;
        // 删除多余的
        delete this.rentForm.rentTime;
        await reqAddRentAPI(this.rentForm);
        this.$notify.success("添加成功!");
        // 更新视图
        this.getEnterpriseList();
        this.closeDialog();
      });
    },
    // 点击
    async expandChange(a, b) {
      console.log(a, b);
      // 展开或者关闭都会触发
      // a里面包含id
      // b是个数组 包括当前所有数据
      // 通过a是否在b数组里面判断是否处于展开状态
      // 返回满足条件的第一个值
      const isInclude = b.find((item) => item.id === a.id);
      if (!isInclude) {
        return;
      }
      const res = await reqGetRentBuildingAPI(a.id);
      a.rentList = res.data;
      console.log(a.rentList);
    },
    handleDelete(id) {
      this.$confirm("确认要删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqDelRentAPI(id);
          console.log(res);
          this.$message.success("删除成功");
          this.getEnterpriseList();
        })
        .catch(() => {});
    },
    // 退租租赁合同
    rentingOut(id) {
      this.$confirm("您确定要退租吗")
        .then(async () => {
          const res = await reqRentingOutAPI(id);
          this.$message.success("退租成功");
          // 刷新列表
          this.getEnterpriseList();
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
